const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

// 获取放置html文字的文件夹路径
const directoryPath = path.join(__dirname, './src/html');
// 需要复制到dist的本地文件夹
const copyFolder = [
  {
    from: path.resolve(__dirname, './src/images'),
    to: path.resolve(__dirname, './dist/images'),
  },
  {
    from: path.resolve(__dirname, './src/local-js'),
    to: path.resolve(__dirname, './dist/js'),
  },
];

// isEveryPagesNeedJs 是否每个html页面都需要有一个自己的js文件
// true 需要  false 不需要
// 如果设置成true的话需要在js文件里新建跟html文件名一样的js文件，否则会报错
// 如果设置成false的话,会默认读取index.js文件
// 如果有需要给每个html页面单独写逻辑的话可以设置成true
const isEveryPagesNeedJs = false;

function getFileName() {
  return new Promise((resolve) => {
    // 动态读取放置html文字的文件夹路径
    fs.readdir(directoryPath, (err, files) => {
      if (err) {
        return console.log('读取文件夹出错:', err);
      }
      let pagesList = [];
      files.forEach((file) => {
        const basename = path.basename(file);
        const ext = path.extname(basename);
        const nameWithoutExt = path.basename(basename, ext);
        if (ext === '.html') {
          pagesList.push(nameWithoutExt);
        }
      });

      function getPagesConfig() {
        const entryObj = {};
        const htmlArr = [];
        pagesList.forEach((item) => {
          entryObj[item] = path.resolve(__dirname, `./src/js/${isEveryPagesNeedJs ? item : 'index'}.js`);
          htmlArr.push(
            new HtmlWebpackPlugin({
              filename: `${item}.html`,
              template: path.resolve(__dirname, `./src/html/${item}.html`),
              chunks: [item],
            }),
          );
        });
        return {
          entryObj,
          htmlArr,
        };
      }

      // 复制本地文件夹到打包文件夹路径的逻辑处理
      function getCopyFolderConfig() {
        const copyFolderArr = [];
        copyFolder.forEach((item) => {
          copyFolderArr.push(
            new CopyPlugin({
              patterns: [
                {
                  from: item.from,
                  to: item.to,
                },
              ],
            }),
          );
        });
        return {
          copyFolderArr,
        };
      }

      const config = {
        mode: 'development',
        entry: {
          ...getPagesConfig().entryObj,
        },
        output: {
          filename: 'js/[name].js',
          path: path.resolve(__dirname, './dist'),
        },
        devServer: {
          static: {
            directory: path.resolve(__dirname, './dist'),
          },
          compress: true,
          port: 9999,
          hot: true,
          watchFiles: ['./src/**/*.html', './src/**/*.ejs'],
        },
        module: {
          rules: [
            {
              test: /\.css$/,
              use: [
                MiniCssExtractPlugin.loader,
                { loader: 'css-loader' },
                {
                  loader: 'postcss-loader',
                },
              ],
            },
            {
              test: /\.(png|svg|jpg|jpeg|gif)$/i,
              type: 'asset',
              parser: {
                dataUrlCondition: {
                  maxSize: 8 * 1024,
                },
              },
              generator: {
                filename: 'images/[name].[hash:6][ext]',
              },
            },
            {
              test: /\.ejs/,
              loader: 'ejs-loader',
              options: {
                esModule: false,
              },
            },
            {
              test: /\.js$/,
              exclude: /node_modules/,
              use: [{ loader: 'babel-loader' }],
            },
          ],
        },
        optimization: {
          minimize: true, //代码压缩
          usedExports: true, // treeshaking
          minimizer: [
            new UglifyJsPlugin(),
            new OptimizeCssAssetsPlugin({
              assetNameRegExp: /\.css$/g,
              cssProcessorOptions: {
                safe: true,
                autoprefixer: { disable: true },
                mergeLonghand: false,
                discardComments: {
                  removeAll: true, // 移除注释
                },
              },
              canPrint: true,
            }),
          ],
          splitChunks: {
            minSize: 5 * 1024,
            chunks: 'all',
            name: 'webpack-public',
            automaticNameDelimiter: '_',
          },
        },
        stats: {
          errorDetails: true,
        },
        plugins: [
          new webpack.HotModuleReplacementPlugin(),
          new MiniCssExtractPlugin({
            filename: 'css/[name].css',
            chunkFilename: 'css/[name].chunk.css',
          }),
          ...getPagesConfig().htmlArr,
          ...getCopyFolderConfig().copyFolderArr,
          new CleanWebpackPlugin(),
        ],
      };
      resolve(config);
    });
  });
}

module.exports = (async () => {
  const res = await getFileName();
  return res;
})();
